package com.zzyl.service.impl;

import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description MemberServiceImpl
 * @Author loe
 * @Date 2024-07-11
 */

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    /**
     * 登录过程
     * @param userLoginRequestDto
     * @return
     */
    @Override
    @Transactional
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        // 1.调用微信端api, 根据code获取OpenId
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());

        // 2.调用微信端api, 获取手机号
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());

        // 3.从数据库根据openId查找
        Member member = memberMapper.selectByOpenId(openId);

        // 4.判断是否找到, 没找到则new一个member封装数据插入
        if(member == null) {
            member = new Member();
            member.setPhone(phone);
            String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(member.getPhone(), 7);
            member.setName(nickName);
            member.setOpenId(openId);
            memberMapper.insertMember(member);
        } else {
            member.setPhone(phone);
            memberMapper.update(member);
        }

        // 将用户id存入token, 返回
        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        String jwtToken = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(), claims);
        return new LoginVo(jwtToken, member.getName());
    }

}
